package com.tyut.controller;

import com.tyut.pojo.Result;
import com.tyut.utils.AliOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class CommonController {
	@Autowired
	private AliOSSUtil aliOssUtil;
	//得到上传路径
	@PostMapping("/upload")
	public Result upload(MultipartFile file){
		log.info("文件上传{}",file);
		try {
			String originalFilename = file.getOriginalFilename();
			String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
			//将图片使用UUID进行重命名，防止上传到阿里云的图片因为命名重复而冲突
			String objectname = UUID.randomUUID().toString() + extension;
			//调用阿里云OSS工具上传图片
			String filePath = aliOssUtil.upload(file.getInputStream(),objectname);
			//图片上传成功，返回文件路径
			return Result.success(filePath);
		} catch (IOException e) {
			log.error("文件上传失败{}",e);
		}
		return Result.error("文件上传失败");
	}
}

